/*
 * Created on 2003-6-18
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package com.framework.jqgrid;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.eportal.util.Tools;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;


/**
 * String的相关处理类
 *
 * @author zqb
 *         <p/>
 *         <p/>
 *         lqf at 2015-6-26
 *         spanJson:目前对Map形式和List<Object>形式都进行格式化
 *         为支持lookup字段
 *         （1）SQL中增加计算字段=lookup的外部字段名称,这样返回的应该是MAP
 *         （2）但是返回Map的话原来类型已经丢失，增加参数：原来的类型
 *         （3）显然List类型的也应该做一样的对查，但是目前暂时不做，以后再说
 */
public abstract class JsonUtil {


    /**
     * 封装json格式数据
     *
     * @param
     * @param
     * @param
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static String spanJson(HttpServletRequest request, List<?> listdata, JqGridPager jqGridPager) throws IllegalArgumentException, IllegalAccessException {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"total\":\"" + jqGridPager.getTotal() + "\",\"page\":\"" + jqGridPager.getPager() + "\",\"records\":\"" + jqGridPager.getRecords() + "\",\"rows\":[");
        if (listdata != null) {
            sb.append(list2Json(listdata));
        }
        sb.append("]}");
        return sb.toString();
    }

    /**
     * list to set json
     *
     * @param
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static String list2Json(List<?> listdata) throws IllegalArgumentException, IllegalAccessException {

        StringBuffer sb = new StringBuffer();
        int j = 0;
        for (Iterator iterator = listdata.iterator(); iterator.hasNext(); ) {
            j++;
            Object object = iterator.next();
            sb.append(obj2Json(object, j, listdata));
        }
        return sb.toString();
    }

    public static String obj2Json(Object object, int j, List<?> listdata) throws IllegalArgumentException, IllegalAccessException {
        StringBuffer sb = new StringBuffer();
        Field[] fields = (object).getClass().getDeclaredFields();// 获取f对象对应类中的所有属性域
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();// 对于每个属性，获取属性名
            fields[i].setAccessible(true);
            Object o = fields[i].get(object); // 获取在对象f中属性fields[i]对应的对象中的变量
            o = o != null ? o : "";
            String type = fields[i].getGenericType().toString();    //获取属性的类型
            if (type.equals("class java.lang.String")) {//如果是string类型的话，有可能是参数值
                String mv = o.toString().replace("\"", "").replace("\'", "");
                o = o != null ? mv.replaceAll("\n", "").replaceAll("chr(13)", "").replaceAll("chr(10)", "").replaceAll("\r", "") : "";

                if (i == 0) {//第1行
                    sb.append("{\"" + varName + "\":\"" + o + "\",");
                } else if (i == fields.length - 1 && j == listdata.size()) {//最后一行，最后一个字段
                    sb.append("\"" + varName + "\":\"" + o + "\"}");
                } else if (i == fields.length - 1) {//最后一个字段
                    sb.append("\"" + varName + "\":\"" + o + "\"},");
                } else {
                    sb.append("\"" + varName + "\":\"" + o + "\",");
                }
                continue;


            } else if (type.indexOf("com.eportal") > 0) {//是否关系映射对象
                if (o.equals("")) {
                    try {
                        o = Class.forName(type.replace("class ", "")).newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }
                StringBuffer sb_ = buildJson(o, i, len - 1, j, listdata.size());
                sb.append(sb_);
                continue;
            } else {
                if (type.equals("class java.util.Date")) {//如果是date类型的话，转化格式
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    if (o != null && !o.equals(""))
                        o = format.format(o);
                }
                if (i == 0) {
                    sb.append("{\"" + varName + "\":\"" + o + "\",");
                } else if (i == fields.length - 1 && j == listdata.size()) {
                    sb.append("\"" + varName + "\":\"" + o + "\"}");
                } else if (i == fields.length - 1) {
                    sb.append("\"" + varName + "\":\"" + o + "\"},");
                } else {
                    sb.append("\"" + varName + "\":\"" + o + "\",");
                }
            }

        }
        return sb.toString();
    }

    /**
     * map形式的数据集
     *
     * @param
     * @param jqGridPager
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static String spanJson(List<?> mapdata, JqGridPager jqGridPager, HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException {
        return spanJson(null, mapdata, jqGridPager, request);
    }

    private static TreeMap tagentMap;
    private static TreeMap tdepartmentMap;
    private static TreeMap tlockMap;

    private static void refreshMap(HttpServletRequest request) {
        TreeMap<String, TreeMap> treeMap = (TreeMap<String, TreeMap>) request.getSession().getServletContext().getAttribute("parameter");
        tagentMap = treeMap.get("tagent");
        tdepartmentMap = treeMap.get("tdepartment");
    }

    /**
     * liqifei add :
     * change spanJson to add elementType
     *
     * @param elementType
     * @param mapdata
     * @param jqGridPager
     * @param request
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static String spanJson(Class elementType, List<?> mapdata, JqGridPager jqGridPager, HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"total\":\"" + jqGridPager.getTotal() + "\",\"page\":\"" + jqGridPager.getPager() + "\",\"records\":\"" + jqGridPager.getRecords() + "\",\"rows\":");
        if (mapdata != null) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
//            if (elementType != null) {
//                doLookupBefore(mapdata, elementType);
//            }
            JSONArray json = JSONArray.fromObject(mapdata, jsonConfig);
            sb.append(json.toString());
        } else {
            sb.append("[]");
        }
        sb.append("}");
        return sb.toString();
    }




    /**
     * map形式的数据集转json
     *
     * @param mapdata
     * @return
     * @author dingyulei
     */
    public static String spanJson(List<?> mapdata) {
        StringBuffer sb = new StringBuffer();
        if (mapdata != null) {
            JSONArray json = JSONArray.fromObject(mapdata);
            sb.append(json.toString());
        } else {
            sb.append("[]");
        }
        return sb.toString();
    }

    /**
     * 从json HASH表达式中获取一个map，改map支持嵌套功能
     *
     * @param jsonString
     * @return
     */
    public static Map getMap4Json(String jsonString) {
        Map valueMap = new HashMap();
        if (jsonString == null) {
            return valueMap;
        }
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        Iterator keyIter = jsonObject.keys();
        String key;
        Object value;


        while (keyIter.hasNext()) {
            key = (String) keyIter.next();
            value = jsonObject.get(key);
            valueMap.put(key, value);
        }

        return valueMap;
    }

    /**
     * 查询条件sql拼装
     *
     * @param jsonString
     * @return
     * @throws UnsupportedEncodingException
     */
    public static void getQueryParameters(String jsonString,
                                          JqGridPager jqGridPager) throws UnsupportedEncodingException {
        if (jsonString != null && !"".equals(jsonString)) {
            StringBuffer sb = new StringBuffer();
            Map map = getMap4Json(jsonString);
            JSONArray rules = (JSONArray) map.get("rules");
            String[] stringArray = getStringArray4Json(rules);
            int i = 0;
            for (String objmap : stringArray) {
                i++;
                Map map_ = getMap4Json(objmap);
                if (!"".equals(URLDecoder.decode((String) map_.get("data"),
                        "utf-8"))) {

                    if (i == 1) {
                        sb.append(" "
                                + map_.get("field")
                                + " "
                                + getOp((String) map_.get("op"))
                                + " "
                                + (Tools.isValidDate(URLDecoder.decode((String) map_.get("data"),
                                "utf-8"), "yyyy-MM-dd") ? "to_date('" + URLDecoder.decode((String) map_.get("data"),
                                "utf-8") + "','yyyy-MM-dd')" : "'" + (map_.get("op").equals("cn") ? "%" : "") + URLDecoder.decode((String) map_.get("data"),
                                "utf-8") + (map_.get("op").equals("cn") ? "%" : "") + "'"));
                    } else {
                        sb.append(" "
                                + map.get("groupOp")
                                + " "
                                + map_.get("field")
                                + " "
                                + getOp((String) map_.get("op"))
                                + " "
                                + (Tools.isValidDate(URLDecoder.decode((String) map_.get("data"),
                                "utf-8"), "yyyy-MM-dd") ? "to_date('" + URLDecoder.decode((String) map_.get("data"),
                                "utf-8") + "','yyyy-MM-dd')" : "'" + (map_.get("op").equals("cn") ? "%" : "") + URLDecoder.decode((String) map_.get("data"),
                                "utf-8") + (map_.get("op").equals("cn") ? "%" : "") + "'"));
                    }
                } else {
                    sb.append(" "
                            + map_.get("field") + " is null");
                }
            }
            if (jqGridPager.getWhere() != null && !(jqGridPager.getWhere()).equals("")) {
                jqGridPager.setWhere(jqGridPager.getWhere() + " and " + sb.toString());
            } else {
                jqGridPager.setWhere(sb.toString());
            }

        }

    }

    /**
     * 从json数组中解析出java字符串数组
     *
     * @param
     * @return
     */
    public static String[] getStringArray4Json(JSONArray jsonArray) {
        String[] stringArray = new String[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            stringArray[i] = jsonArray.getString(i);

        }

        return stringArray;
    }

    /**
     * 查询类型解析
     *
     * @param
     * @return
     */
    public static String getOp(String op) {
        String op_ = "";
        if (op.equalsIgnoreCase("eq")) {//等于
            op_ = "=";
        } else if (op.equalsIgnoreCase("ne")) {//不等于
            op_ = "!=";
        } else if (op.equalsIgnoreCase("lt")) {//小于
            op_ = "<";
        } else if (op.equalsIgnoreCase("le")) {//小于等于
            op_ = "<=";
        } else if (op.equalsIgnoreCase("gt")) {//大于
            op_ = ">";
        } else if (op.equalsIgnoreCase("ge")) {//大于等于
            op_ = ">=";
        } else if (op.equalsIgnoreCase("cn")) {//包含
            op_ = "like";
        }

        return op_;
    }

    /**
     * 拼装json数据
     *
     * @param
     * @param i--第几列
     * @param j--第几行
     * @param k--总行数
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static StringBuffer buildJson(Object object, int i, int length, int j, int k) throws IllegalArgumentException, IllegalAccessException {
        StringBuffer sb = new StringBuffer();
        Field[] fields = (object).getClass().getDeclaredFields();// 获取f对象对应类中的所有属性域
        String classname = (object).getClass().getSimpleName();
        for (int i_ = 0, len = fields.length; i_ < len; i_++) {
            String varName = fields[i_].getName();// 对于每个属性，获取属性名
            if (varName.equals("id")) {
                continue;
            }
            fields[i_].setAccessible(true);
            Object o = fields[i_].get(object); // 获取在对象f中属性fields[i]对应的对象中的变量
            o = o != null ? o : "";
            String type = fields[i_].getGenericType().toString();    //获取属性的类型
            if (type.equals("class java.lang.String")) {//如果是string类型的话，有可能是参数值
                String mv = (String) o;
                o = o != null ? mv.replaceAll("\n", "").replaceAll("chr(13)", "").replaceAll("chr(10)", "").replaceAll("\r", "") : "";

                if (i == 0) {//第1行
                    sb.append("{\"" + classname + "." + varName + "\":\"" + o + "\",");
                } else if (fields.length - 1 == i_ && i == length && j == k) {//最后一行，最后一个字段
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\"}");
                } else if (fields.length - 1 == i_ && i == length) {//最后一个字段
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\"},");
                } else {
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\",");
                }
                continue;


            } else {
                if (type.equals("class java.util.Date")) {//如果是date类型的话，转化格式
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    if (o != null && !o.equals(""))
                        o = format.format(o);
                }
                if (i == 0) {
                    sb.append("{\"" + classname + "." + varName + "\":\"" + o + "\",");
                } else if (fields.length - 1 == i_ && i == length && j == k) {//最后一行，最后一个字段
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\"}");
                } else if (fields.length - 1 == i_ && i == length) {//最后一个字段
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\"},");
                } else {
                    sb.append("\"" + classname + "." + varName + "\":\"" + o + "\",");
                }
            }

        }
        return sb;
    }
}
